package com.oa.gform.client.ui;

import java.util.Collection;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.user.client.ui.TextBox;
import com.oa.gform.client.ui.formatter.GetValueFormatterFactory;
import com.oa.gform.client.ui.formatter.ToStringFormatter;
import com.oa.gform.client.ui.formatter.ValueFormatter;
import com.oa.gform.client.validator.GValidationCallback;
import com.oa.gform.client.validator.GValidator;


public class GFieldTextBox<T> extends TextBox implements GField<T>  {
	GBaseFieldImpl<T> baseFieldImpl = new GBaseFieldImpl<T>(this);
	ValueFormatter<T,String> getValueFormatter ;
	ToStringFormatter<T> setValueFormatter = new ToStringFormatter<T>();

	/***
	 * Costruttore di default
	 */
	public GFieldTextBox() {
		super();
		this.addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				GFieldTextBox.this.Validate(null);
			}
		});
	}
	
	public void setFieldName(String fieldName) {
		baseFieldImpl.setFieldName(fieldName);
	}

	public String getFieldName() {
		return baseFieldImpl.getFieldName();
	}

	public String[] getFieldGroupNames() {
		return baseFieldImpl.getFieldGroupNames();
	}

	public void setFieldGroupNames(String... fieldGroupNames) {
		baseFieldImpl.setFieldGroupNames(fieldGroupNames);
	}

	public boolean isInGroupName(String fieldGroupName) {
		return baseFieldImpl.isInGroupName(fieldGroupName);
	}
	
	public GFieldLabel getGFieldLabel() {
		return baseFieldImpl.getGFieldLabel();
	}

	public void setGFieldLabel(GFieldLabel gfieldLabel) {
		baseFieldImpl.setGFieldLabel(gfieldLabel);
	}
	
	public void addGValidator(GValidator validator) {
		baseFieldImpl.addGValidator(validator);
	}

	public void addGValidators(Collection<GValidator> collection) {
		baseFieldImpl.addGValidators(collection);
	}
	
	@Override
	public void setInError(boolean inError) {
		baseFieldImpl.setInError(inError);
	}

	@Override
	public void Validate(GValidationCallback gValidationCallback) {
		baseFieldImpl.Validate(gValidationCallback);
	}

	@Override
	public void reset() {
		baseFieldImpl.reset();
		setValue("");
	}

	@Override
	public void setFieldValue(T fieldValue) {
		baseFieldImpl.setFieldValue(fieldValue);
		setValue(setValueFormatter.format(fieldValue));
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getFieldValue() {
		if (getValueFormatter==null) {
			getValueFormatter = (ValueFormatter<T, String>) GetValueFormatterFactory.create(baseFieldImpl.getFieldValue(),getValue());
		}
		return getValueFormatter.format(this.getValue());
	}


	
}
